
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
/*启动20000个线程对num进行累加,模拟多线程并发*/

// 定义线程数量
#define THREAD_COUNT 20000

void *thread_fun(void *arg)
{
    int *num = (int *)arg;
    *num = *num + 1;
    return NULL;
}

int main(int argc, char const *argv[])
{

    // 1.创建线程
    pthread_t ptr[THREAD_COUNT];
    int num = 0;
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_create(ptr + i, NULL, thread_fun, &num);
    }

    // 2.等待线程结束
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_join(ptr[i], NULL);
    }

    printf("累加和为:%d\n", num);

    return 0;
}
